/*
 * @Author: xiaosihan
 * @Date: 2021-03-28 02:13:06
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2025-09-16 16:59:59
 */

import Taro from "@tarojs/taro";
import Api from "src/api/Api";
import smallLogoPNG from "src/static/smallLogo.png";
import path from 'path-browserify';
import CryptoJS from 'crypto-js';

// 全局公共方法
class Utils {
    constructor() { }

    isH5 = false; //浏览器

    // 开发版
    isDev = Taro.getAccountInfoSync().miniProgram.envVersion === "develop";
    // 体验版
    isTrial = Taro.getAccountInfoSync().miniProgram.envVersion === "trial";
    // 线上版
    isRelease = Taro.getAccountInfoSync().miniProgram.envVersion === "release";

    isIPhone = Taro.getDeviceInfo().brand === "iPhone"; // 是否苹果手机

    // 判断是否是华为
    isHuawei = Taro.getDeviceInfo().brand === "HUAWEI";

    // pixelRatio = Taro.getWindowInfo().pixelRatio; // 分辨率

    // isProd = Taro.getDeviceInfo() === 'release';
    // 是否为体验版

    //url解析
    //url解析
    parseUrl(url: string) {
        const _parsed = path.parse(url);
        return {
            // hash: _url.hash,
            // host: _url.host,
            // hostname: _url.hostname,
            // href: _url.href,
            // origin: _url.origin,
            // pathname: _url.pathname,
            // port: _url.port,
            // protocol: _url.protocol,
            // search: _url.search,

            base: _parsed.base,
            dir: _parsed.dir,
            ext: _parsed.ext,
            name: _parsed.name,
            root: _parsed.root,
        }
    }

    ossSuffix(src: string = "", maxSide?: number, cdnSuffix: boolean = true) {

        // 输入空,就直接返回空
        if (!src) {
            return src;
        }

        // 确保src以http或https开头
        let newSrc = src;
        if (!src.startsWith('http://') && !src.startsWith('https://')) {
            // 如果不是完整URL，使用ossRoot作为基础
            if (!src.startsWith('/')) {
                newSrc = `/${newSrc}`;
            }
            newSrc = newSrc.replace(Api.ossRoot, "");
            newSrc = `${Api.ossRoot}${newSrc}`;
        }

        // 移除可能存在的处理参数
        newSrc = newSrc
            .replace(/(\?|&)(image_process=.*?)(?=&|$)/, '')
            .replace(/(\?|&)(x-oss-process=.*?)(?=&|$)/, '')

        // 不处理占位图
        if (newSrc === './UTlogo.svg') {
            newSrc = smallLogoPNG;
        }

        // 添加图片处理参数（仅对非SVG图片）
        if (maxSide && !newSrc.endsWith('.svg') && !newSrc.endsWith(smallLogoPNG)) {
            if (cdnSuffix) {
                const fileName = this.parseUrl(newSrc).name;
                const [width, height] = fileName.split("_");
                newSrc += `?image_process=resize,w_${maxSide}`;
                // newSrc += `?image_process=resize,${width > height ? 'w' : 'h'}_${maxSide}`;
            } else {
                newSrc += `?x-oss-process=image/resize,m_lfit,w_${maxSide},h_${maxSide}`;
            }
        }

        // 确保URL格式正确
        if (!newSrc.startsWith('http://') && !newSrc.startsWith('https://')) {
            newSrc = `https:${newSrc}`;
        }

        return newSrc;
    }

    // 数字加千分位
    thousand(number = 0, dot = 0) {
        let strNum = String(Number(Number(number).toFixed(dot))); // 转化成字符串
        while (strNum !== strNum.replace(/(\d)(\d{3})(\.|,|$)/, "$1,$2$3")) {
            strNum = strNum.replace(/(\d)(\d{3})(\.|,|$)/, "$1,$2$3");
        }
        return strNum;
    }

    // 取随机数在某个范围里
    rand(start: number, end: number) {
        return Math.floor(Math.random() * (end - start + 1) + start);
    }

    //随机数组
    randArray(array: Array<any>) {
        return array[this.rand(0, array.length - 1)];
    }

    // 字符串转json
    JSONParse(jsonString) {
        try {
            return JSON.parse((jsonString || "{}").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g,
                "\\t"));
        } catch (error) {
            return {};
        }
    }

    /**
     * 选文件
     */
    async selectFile(count = 1) {
        const url = await new Promise<Taro.chooseImage.SuccessCallbackResult>((resolve) => {
            Taro.chooseImage({
                count,
                sizeType: ["original"], // , "compressed"
                sourceType: ["album", "camera"], //相册、相机
                success: (res) => {
                    resolve(res);
                },
                fail: () => {
                    // resolve(undefined);
                },
            });
        });

        return url;
    }

    rpx2px(rpx: number) {
        const { windowWidth } = Taro.getSystemInfoSync();
        return rpx * windowWidth / 750;
    }

    vw2px(vw: number) {
        const { windowWidth } = Taro.getSystemInfoSync();
        return (vw / 100) * windowWidth;
    }

    // 字符串md5加密
    md5(str: string) {
        const md5Hash = CryptoJS.MD5(str).toString();
        return md5Hash;
    }


}

const utils = new Utils();

export default utils;